﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;

using CE.Database;
using CE.CarInsurance;
using CE.Configuration;
using CE.Mail;
using CE.Global;
using System.Net;
using System.Text;
public partial class Quote_Result : MyLanguageBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[General.CarId] != null && Session[General.CarId] != "")
        {
            if (!Page.IsPostBack)
            {
                if (Session[General.UserId] != null)
                {
                    Cache.Remove("CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString());
                }
                else
                {
                    Cache.Remove("CarResult" + Session[General.CarId].ToString());
                }
                if (Session["IsFromAutoLogin"] == null || Session["IsFromAutoLogin"].ToString() != "1")
                    CalculatePremium();
                GetTempResultTableTwo();
            }

        }
        else
        {
            Response.Redirect("quote.aspx");
        }


    }

    private Int32 CalculatePremium()
    {
        Int32 _result = 0;
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();

        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        Int64 _userId = 0;
        if (Session[General.UserId] != null)
        {
            _userId = Convert.ToInt64(Session[General.UserId].ToString());
        }
        _sPara.Add("@CarId", _carId);
        _sPara.Add("@RefUserId", _userId);
        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);

        //select car detail
        _db = new MyDatabase();
        _sPara = new SortedList();
        DataTable _dt = new DataTable("tblModelBody");
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", _userId);
        _dt = _db.GetDataTableBySP("[sprocCarDetailTHSelectSingleItem]", _sPara);
        string[] makeName;
        makeName = _dt.Rows[0]["MakeModelDesc"].ToString().Split(' ');

        
        #region KawnaPackage
        try
        {
            if (IsKawnaCar(makeName[0]))
            {
                DataTable dtPackage = new DataTable();

                CarPolicy _carpolicy = new CarPolicy();
                CarPolicyDB _carpolicydb = new CarPolicyDB();
                _carpolicy = _carpolicydb.GetCarPolicy(_carId, _userId);
                string strProviderList = "";

                string strCarProvince = _carpolicy.ProvinceRegistration == "BKK" ? "1" : "79";
                string strDriverAge1 = "", strDriverAge2 = "";
                int DriverAge1 = 0, DriverAge2 = 0;
                if (_carpolicy.IsAddDriver == true)
                {
                    CarDriverList _cardriverlist = new CarDriverList();
                    CarDriverDB _cardriverdb = new CarDriverDB();
                    _cardriverlist = _cardriverdb.GetCarDriverList(_carId, _userId);
                    _cardriverdb = null;
                    int _noOfDriver = _carpolicy.NoOfDriver;
                    for (int i = 1; i <= _noOfDriver; i++)
                    {
                        CarDriver _cardriver = _cardriverlist[i - 1];
                        if (i == 1)
                        {
                            DriverAge1 = General.GetUTCDateTime().Year - _cardriver.DOB.Year;
                        }
                        else if (i == 2)
                        {
                            DriverAge2 = General.GetUTCDateTime().Year - _cardriver.DOB.Year;
                        }
                    }
                    _cardriverlist = null;

                    if (DriverAge1 >= 18 && DriverAge1 <= 24)
                        strDriverAge1 = "18";
                    else if (DriverAge1 >= 25 && DriverAge1 <= 35)
                        strDriverAge1 = "25";
                    else if (DriverAge1 >= 36 && DriverAge1 <= 50)
                        strDriverAge1 = "36";
                    else if (DriverAge1 > 50)
                        strDriverAge1 = "50";

                    if (_noOfDriver == 2)
                    {
                        if (DriverAge2 >= 18 && DriverAge2 <= 24)
                            strDriverAge2 = "18";
                        else if (DriverAge2 >= 25 && DriverAge2 <= 35)
                            strDriverAge2 = "25";
                        else if (DriverAge2 >= 36 && DriverAge2 <= 50)
                            strDriverAge2 = "36";
                        else if (DriverAge2 > 50)
                            strDriverAge2 = "50";
                    }

                }

                HttpWebRequest request;
                string kawnaModel = GetKawnaModelValue(makeName[0], _dt.Rows[0]["CarModel"].ToString() + " " + String.Format("{0:0.0}", (Convert.ToInt32(_dt.Rows[0]["CC"]) * 0.001)) + "cc " + _dt.Rows[0]["Door"].ToString() + " Door");
                string tun = GetKawnaSingleSumInsured(makeName[0], kawnaModel, _dt.Rows[0]["ManufactYear"].ToString());
                if (tun == "0") tun = "";
                string url = _url + "?brand=" + makeName[0].ToString() + "&id_motor=" + kawnaModel.ToString() + "&yearcar=" + _dt.Rows[0]["ManufactYear"].ToString() + "&tun=" + tun + "&Yins=0&dee=0&country=" + strCarProvince + "&rgb=" + strCarProvince + "&paper=no&plantry=&oldinsure=&clame=" + (_carpolicy.IsClaimLastYear == false ? "ไม่มีเครม" : "มีเครม+ไม่มีคู่กรณี") + "&rabu=" + (_carpolicy.IsAddDriver == true ? "yes" : "") + "&old1=" + strDriverAge1 + "&old2=" + strDriverAge2 + "&t=submit";
                string responseBody = string.Empty;
                string requestBody = "";
                byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
                request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.ContentType = "application/xml;charset=utf-8";
                request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
                request.Accept = "*/*";
                request.Method = "POST";
                request.ContentLength = byteData.Length;
                System.Net.ServicePointManager.Expect100Continue = false;
                request.KeepAlive = false;

                string startTime = DateTime.Now.ToString("HH:mm:ss.ff tt dd/MM/yyyy");
                DateTime sTime = DateTime.Now;
                DataTable dtIns = new DataTable();
                DataSet ds = new DataSet();
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    ds.ReadXml(response.GetResponseStream());
                }
                dtPackage = ds.Tables["Pre"];
                DataTable dt = ds.Tables["INS"];
                dtIns = dt.Clone();
                dtIns = dt.Copy();

                // *** Start Join Table ***
                DataTable dtblResult = dtPackage.Clone();
                dtblResult.Columns.Add("InsName", typeof(string));
                dtblResult.Columns.Add("INS_Text", typeof(string));
                dtblResult.Columns.Add("PRE_IdIns", typeof(string));

                //get row data
                var rowData = from row1 in dtPackage.AsEnumerable()
                              join row2 in dtIns.AsEnumerable()
                              on row1["PRE_Id"] equals row2["PRE_Id"]
                              select row1.ItemArray.Concat(row2.ItemArray).ToArray();

                //Add row data to dtblResult
                foreach (object[] values in rowData)
                    dtblResult.Rows.Add(values);

                //Change column name back to original
                dtblResult.Columns["INS_Text"].ColumnName = "INS";

                //Remove extra column from result
                dtblResult.Columns.Remove("PRE_IdIns");
                dtblResult.Columns.Add("PROPRICE", typeof(Double));
                dtPackage.Dispose();
                dtPackage = new DataTable();
                dtPackage = dtblResult.Clone();
                dtPackage.Columns["PRICE"].DataType = typeof(string);
                //dtPackage = dtblResult.Copy();
                foreach (DataRow row in dtblResult.Rows)
                {
                    dtPackage.ImportRow(row);
                }

                dtblResult.Dispose();
                dtIns.Dispose();
                // *** End Join Table ***
                _db = new MyDatabase();
                _sPara = new SortedList();
                DataTable _dtPvdList = new DataTable();
                _dtPvdList = _db.GetDataTable("SELECT ProviderId FROM tblKawnaProvider WHERE ProviderCompanyId IS NOT NULL");

                foreach (DataRow dr in _dtPvdList.Rows)
                {
                    if (strProviderList != null && strProviderList != "")
                        strProviderList += ",";
                    strProviderList += dr["ProviderId"];
                }
                var strExpr = " INS IN(" + strProviderList + ") ";

                if (_carpolicy.InsuranceType == 10 || _carpolicy.InsuranceType == 11)
                    strExpr += " AND POTYPE = 'ป1' ";
                else if (_carpolicy.InsuranceType == 21)
                    strExpr += " AND POTYPE = 'ป2+' ";
                else if (_carpolicy.InsuranceType == 31)
                    strExpr += " AND POTYPE = 'ป3+' ";
                else if (_carpolicy.InsuranceType == 30)
                    strExpr += " AND POTYPE = 'ป3' ";

                if (_carpolicy.GarageType > 0 && _carpolicy.InsuranceType != 30)
                {
                    strExpr += " AND FIX = ";
                    strExpr += _carpolicy.GarageType.ToString() != "1" ? "'ห้าง' " : "'อู่' ";
                }
                if (_carpolicy.InsuranceType != 30)
                {
                    if (_carpolicy.Deductible == 0)
                        strExpr += " AND (ODDD = '' OR ODDD IS NULL)";
                    else if (_carpolicy.Deductible > 0)
                        strExpr += " AND ODDD <> ''";
                }
                if (_carpolicy.InsuranceType == 30)
                {
                    if (_carpolicy.IsCTPL == true)
                        strExpr += " AND (CMI_INCLUDE = 'yes' )";
                    else
                        strExpr += " AND (CMI_INCLUDE <> 'yes' )";
                }
                var strSort = " PRICE ASC, TUN ASC ";
                DataView dv = new DataView(dtPackage);

                dv.RowFilter = strExpr;
                dv.Sort = strSort;

                var query = (from order in dv.ToTable().AsEnumerable()
                             group order by order["INS"] into grp
                             let fewItems = grp.Take(3).ToList()
                             select fewItems.CopyToDataTable());

                DataTable boundTable = new DataTable();
                boundTable = dv.ToTable().Clone();
                foreach (var rsv in query)
                {
                    for (int i = 0; i < rsv.Rows.Count; i++)
                        boundTable.ImportRow(rsv.Rows[i]);
                }
                foreach (DataRow drc in boundTable.Rows)
                {
                    _db = new MyDatabase();
                    _sPara = new SortedList();
                    _sPara.Add("FromSource", "W");
                    _sPara.Add("CarId", Convert.ToInt64(Session[General.CarId]));
                    _sPara.Add("ProviderId", drc["INS"].ToString() != "" ? Convert.ToInt32(drc["INS"]) : 0);
                    _sPara.Add("PackageId", drc["PACKID"].ToString() != "" ? Convert.ToInt32(drc["PACKID"]) : 0);
                    _sPara.Add("PackageName", drc["PACKNAME"].ToString());
                    _sPara.Add("TotalPremium", drc["PRICE"].ToString() != "" ? Convert.ToDouble(drc["PRICE"]) : 0.0);
                    _sPara.Add("TotalVMI", drc["PRICE"].ToString() != "" ? Convert.ToDouble(drc["PRICE"]) : 0.0);
                    _sPara.Add("IsIncludeCMI", drc["CMI_INCLUDE"].ToString() != "" ? true : false);
                    _sPara.Add("TPPD", drc["TP"].ToString() != "" ? (Convert.ToInt64(drc["TP"].ToString().Replace(",", ""))) : 0);
                    _sPara.Add("TPBIP", drc["BT"].ToString().ToString() != "" ? (Convert.ToInt64(drc["BT"].ToString().Replace(",", ""))) : 0);
                    _sPara.Add("TPBIA", drc["BI"].ToString().ToString() != "" ? (Convert.ToInt64(drc["BI"].ToString().Replace(",", ""))) : 0);
                    _sPara.Add("DEC", drc["ODDD"].ToString().Trim() != "" ? Convert.ToDouble(drc["ODDD"].ToString().Trim()) : 0);
                    _sPara.Add("SumInsured", drc["TUN"].ToString() != "" ? Convert.ToInt64(drc["TUN"].ToString()) : 0);
                    _sPara.Add("FireAndTheft", drc["FIRE"].ToString() != "" ? Convert.ToDouble(drc["FIRE"].ToString()) : 0.0);
                    _sPara.Add("Theft", drc["TUN"].ToString() != "" ? Convert.ToInt64(drc["TUN"].ToString()) : 0);
                    _sPara.Add("PADriver", drc["PA"].ToString() != "" ? (Convert.ToDouble(drc["PA"].ToString().Replace(",", ""))) : 0.0);
                    _sPara.Add("PAPassenger", drc["PA"].ToString() != "" ? (Convert.ToDouble(drc["PA"].ToString().Replace(",", ""))) : 0.0);
                    _sPara.Add("MED", drc["ME"].ToString() != "" ? (Convert.ToDouble(drc["ME"].ToString().Replace(",", ""))) : 0.0);
                    _sPara.Add("BailBond", drc["BB"].ToString() != "" ? (Convert.ToDouble(drc["BB"].ToString().Replace(",", ""))) : 0.0);
                    _sPara.Add("RefUserId", Convert.ToDouble(Session[General.UserId].ToString()));
                    _sPara.Add("IsSpecialOffer", 0);
                    _sPara.Add("IsFloodCover", drc["FLOOD"].ToString().Trim() != "" ? 1 : 0);
                    _sPara.Add("GarageType", drc["FIX"].ToString().Trim() != "" && drc["FIX"].ToString().Trim() == "ห้าง" ? 1 : 0);
                    _sPara.Add("CarType", _dt.Rows[0]["Body"].ToString());
                    _sPara.Add("CarDoors", _dt.Rows[0]["Door"].ToString() != "" ? Convert.ToInt32(_dt.Rows[0]["Door"].ToString()) : 4);
                    _sPara.Add("@PeopleCovered", drc["P"].ToString().Trim() != "" ? drc["P"].ToString().Trim() : "0");
                    _result = _db.ExecuteNonSqlSP("[sprocKawnaSaveResultPackages]", _sPara);

                }
                return _result;
            }
        }
        catch { }

        #endregion
        //====Test Web Service
        BKIDetailDB bki = new BKIDetailDB();
        try
        {
            bki.BKICalculation(_carId, _userId);
        }
        catch
        {
        }
        _db = new MyDatabase();
        _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefUserId", _userId);

        _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculation]", _sPara);

        return _result;
    }

    protected void dlCarResults_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ||
             e.Item.ItemType == ListItemType.AlternatingItem)
        {
            ImageButton imgEmailQuote = (ImageButton)e.Item.FindControl("imgEmailQuote");
            imgEmailQuote.Attributes.Add("onclick", "return confirm('Are you sure you want to send this quote?');");

            Label lblPremiumAmount = (Label)e.Item.FindControl("lblPremiumAmount");
            Label lblPromotionPrice = (Label)e.Item.FindControl("lblPromotionPrice");

            Label lblProviderCompanyName = (Label)e.Item.FindControl("lblProviderCompanyName");

            Label lblPlanName = (Label)e.Item.FindControl("lblPlanName");
            Label lblProviderCompanyID = (Label)e.Item.FindControl("lblProviderCompanyID");
            Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");
            Image imgProviderCompanyLogo = (Image)e.Item.FindControl("imgProviderCompanyLogo");

            Label lblSpecialNBC = (Label)e.Item.FindControl("lblSpecialNBC");

            string _promotionPrice = DataBinder.Eval(e.Item.DataItem, "PromotionPrice").ToString().Trim();
            string _premiumAmount = DataBinder.Eval(e.Item.DataItem, "AnnualPremium").ToString().Trim();

            lblPromotionPrice.Text = "(฿) " + Convert.ToSingle(_promotionPrice).ToString("#,000.00");

            if (_promotionPrice != _premiumAmount)
            {
                lblPremiumAmount.Text = "(฿) " + Convert.ToSingle(_premiumAmount).ToString("#,000.00");
            }
                       
            lblProviderCompanyID.Text = DataBinder.Eval(e.Item.DataItem, "ProviderCompanyId").ToString();
            lblProviderCompanyName.Text = DataBinder.Eval(e.Item.DataItem, "CompanyName").ToString();
            lblPlanName.Text = DataBinder.Eval(e.Item.DataItem, "PackageName").ToString();
            lblCarResultID.Text = DataBinder.Eval(e.Item.DataItem, "CITempResultID").ToString();

            HyperLink hlnkView = (HyperLink)e.Item.FindControl("hlnkView");
            hlnkView.NavigateUrl = "~/Quote_Result_Detail.aspx?crid=" + lblCarResultID.Text;

            HyperLink hlnkViewTop = (HyperLink)e.Item.FindControl("hlnkViewTop");
            hlnkViewTop.NavigateUrl = "~/Quote_Result_Detail.aspx?crid=" + lblCarResultID.Text;
            Literal imgSpecial = (Literal)e.Item.FindControl("lblSpecial");
            System.Web.UI.HtmlControls.HtmlGenericControl divPrice = (System.Web.UI.HtmlControls.HtmlGenericControl)e.Item.FindControl("divbgimage");
            if (lblPlanName.Text != "GluayGluay.com Special")
            {
                imgProviderCompanyLogo.ImageUrl = "http://www.gluaygluay.com" + DataBinder.Eval(e.Item.DataItem, "CompanyLogoServerUrl").ToString();
            }
            else
            {
                lblSpecialNBC.Text = "<br/>" + Resources.CarInsurance.SpecialNCB;
                imgProviderCompanyLogo.ImageUrl = "~/images/public/gluaygluay.png";
                imgProviderCompanyLogo.AlternateText = "GluayGluay.com";
                imgSpecial.Text = "<img src='images/bg/special_offer.png' alt='Special Offer' style='border-width:0px' /><br />";
                divPrice.Attributes.Add("class", "right pricenotop");
            }
        }   
    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultSelectItemList]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());

        if (Session["UserID"] != null)
        {
            _sPara.Add("@RefUserId", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefUserId", 0);
        }

        _dtResult = _db.GetDataTableBySP(_spName, _sPara);

        dlCarResults.DataSource = null;
        dlCarResults.DataSource = _dtResult;
        dlCarResults.DataBind();

        if (Session[General.UserId] != null)
        {
            if (Session[General.CarId] != null)
            {
                Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;
            }
        }
        else
        {
            if (Session[General.CarId] != null)
            {
                Cache["CarResult" + Session[General.CarId].ToString()] = _dtResult;
            }
        }

        if (dlCarResults.Items.Count <= 0)
        {
            lblNoResultMessage.Text = "<div class='pad_10'><h2>No Matches Found!</h2><span class='font_12'><strong>Please take note that there are no matches found based on your details entered.</strong></span><div class='seperator'></div><div class='seperator'></div>You can also return to our <a href='/'>homepage</a> or our dedicated <a href='quote.aspx'>car insurance quote</a> page to re-quote.<div class='seperator'></div>Thank you for using กล้วยๆ.com.</div>";
        }
        else
        {
            lblNoResultMessage.Text = "( " + dlCarResults.Items.Count + " ) packages found <br/><br/>";
        }
    }

    protected void dlCarResults_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName == "Email")
        {
           Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");

            this.EmailQuote(lblCarResultID.Text);

        }



        if (e.CommandName == "ViewDetails")
        {
            Label lblCarResultID = (Label)e.Item.FindControl("lblCarResultID");

            if (lblCarResultID.Text.Trim() != "")
            {
                Response.Redirect("quote_result_detail.aspx?crid=" + lblCarResultID.Text);
            }
        }
    }

    private void EmailQuote(string carresultid)
    {
        string qs_carselected = carresultid;
        string _makemodel = "";
        string _garagetype = "";
        string _caryear = "";
        string _ncb = "";
        string _policystartdate = "";

        Int64 _cecarid = 0;

        if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
        {
            _cecarid = Convert.ToInt64(Session[General.CarId]);
            Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }

            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

            if (_cardetail != null)
            {
                if (_cardetail.MakeModelDesc != null && _cardetail.MakeModelDesc != "")
                    _makemodel = _cardetail.MakeModelDesc;
                else
                    _makemodel = _cardetail.CarModelName + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                _caryear = _cardetail.ManufactYear.ToString();
            }

            if (_carpolicy != null)
            {
                if (_carpolicy.GarageType.ToString().Trim() == "1")
                    _garagetype = Resources.CarInsurance.Garage_Authorized;
                else
                    _garagetype = Resources.CarInsurance.Garage_Dealer;

                _ncb = _carpolicy.NCDPercent.ToString();
                _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
            }
        }

        string _refno = "";
        string _companyName = "";
        string _insurerimageurl = "";
        string _package = "";
        string _annualprice = "";
        string _excess = "";

        bool _isDamageShowImage = false;
        string _damage = "";
        bool _isFireShowImage = false;
        string _fire = "";
        bool _isTheftShowImage = false;
        string _theft = "";
        string _medicalexp = "";
        string _losspe = "";
        string _lossuse = "";
        string _padriver = "";
        string _tppd = "";
        string _bailbond = "";
        bool _isFloodCovered = false;

        if (qs_carselected != "" && Session[General.UserId] != null && Session[General.CarId] != null && Session[General.UserName] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
            {
                DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);

                

                string CITempResultId = qs_carselected; 

                dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                DataTable dtFiltered = dv.ToTable();
                if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
                {
                    if (dtFiltered.Rows.Count > 0)
                    {
                        int rowCount = dtFiltered.Rows.Count;

                        for (int iRows = 0; iRows < rowCount; iRows++)
                        {
                            string _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                            _refno = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid, dtFiltered.Rows[iRows]["packagename"].ToString());

                            if (dtFiltered.Rows[iRows]["packagename"].ToString() != "GluayGluay.com Special")
                            {
                                if (Session["Language"] != null)
                                {
                                    if (Session["Language"].ToString() == "th-TH")
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "1");
                                    else
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }
                                else
                                {
                                    //english
                                    _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }

                                _insurerimageurl = "http://www.gluaygluay.com/" + CE.Global.General.GetProviderCompanyLogo(_providercompanyid);
                            }
                            else
                            {
                                _companyName = "";

                                _insurerimageurl = System.Configuration.ConfigurationSettings.AppSettings["TH.MobileUrl"].ToString() + "/images/public/logo/gluaygluay_logo.png";
                            }

                            _package = "<strong>" + dtFiltered.Rows[iRows]["packagename"].ToString() + "</strong>";


                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"]) != Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"]))
                            {
                                _annualprice = "<s>" + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"].ToString())) + "</s>";
                            }

                            _annualprice = _annualprice + "<div style='color:#F00;font-size:20px;font-weight:bold;' >";
                            _annualprice = _annualprice + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"].ToString())); //"999.00";
                            _annualprice = _annualprice + "</div>";
                                                       
                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()) == 0)
                            {
                                _excess = Resources.CarInsuranceResultPage.Waived;
                            }
                            else
                            {
                                _excess = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()));
                            }

                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString()) == 0)
                            {
                                _isDamageShowImage = true;
                            }
                            else
                            {
                                _damage = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString()));
                            }


                            if (Convert.ToInt32(dtFiltered.Rows[iRows]["Fire"].ToString()) == 0)
                                _isFireShowImage = true;
                            else
                                _fire = String.Format("{0:#,0}", Convert.ToInt32(dtFiltered.Rows[iRows]["Fire"].ToString()));

                            //Theft
                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["Theft"].ToString()) == 0)
                                _isTheftShowImage = true;
                            else
                                _theft = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["Theft"].ToString()));

                            _tppd = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPPD"].ToString()));

                            _losspe = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPBIA"].ToString()));

                            _lossuse = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPBIP"].ToString()));

                            _padriver = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["PADriver"].ToString()));

                            _medicalexp = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["MedicalExpense"].ToString()));

                            _bailbond = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["BailBond"].ToString()));

                            if (dtFiltered.Rows[iRows]["IsFloodCover"].ToString() != "0")
                            {
                                _isFloodCovered = true;
                            }
                        }
                    }
                    else
                    {
                        if (Session["Language"] != null && Session["Language"].ToString() == "en-US")
                             ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert('Session Expired! Please select package again'); window.location ='viewresulthistory.aspx';", true);
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, this.GetType(), "alert", "alert('เซสชั่นหมดอายุกรุณาเลือกเบี้ยประกันใหม่อีกครั้ง'); window.location ='viewresulthistory.aspx';", true);
                        }
                        return;
                    }
                }
                else
                {
                    Response.Redirect("viewresulthistory.aspx");
                }
            }
            else
            {
                Response.Redirect("viewresulthistory.aspx");
            }
        }
        string _emailList = "", _title = "";
        System.Text.StringBuilder _message = new System.Text.StringBuilder();
        _emailList = Session[CE.Global.General.UserEmail].ToString();
        string _currentDomainUrl = "http://www.gluaygluay.com/";
        _title = "";

        _title = "gluaygluay.com (Ref No : " + _refno + ")";

        _message.Append("<table cellpadding='0' cellspacing='0' border='0' width='270' style='font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:0 auto;'>");
        _message.Append("<tr><td style='border-bottom:1px solid #ccc;' align='center'><img src='" + _currentDomainUrl + "mobile/images/bg/logo_gluaygluay.png' alt='' height='78' /><br/><br/>");
        _message.Append("Thank you for choosing GluayGluay.com <br/><strong>Here is your Quote Details </strong><br /><br/></td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><br /><table cellspacing='0' cellpadding='2' width='100%' border='0'>");

        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.QuoteReferenceNumber + "</td>");
        _message.Append("<td valign='top'><strong><u>" + _refno + "</u></strong></td></tr>");

        _message.Append("<tr><td width='50%' valign='top'> " + Resources.ProposalForm.GarageType + " </td>");
        _message.Append("<td width='50%' valign='top'><strong>" + _garagetype + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.CarMakeModel + "</td>");
        _message.Append("<td valign='top'><strong>" + _makemodel + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.CarModelYear + "</td>");
        _message.Append("<td valign='top'><strong>" + _caryear + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.CoverCommencementDate + "</td>");
        _message.Append("<td valign='top'><strong>" + _policystartdate + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.NCB + "</td>");
        _message.Append("<td valign='top'><strong>" + _ncb + "</strong></td></tr>");

        _message.Append("<tr><td valign='top'>" + Resources.ProposalForm.QuoteDate + "</td>");
        _message.Append("<td valign='top'><strong>" + General.GetUTCDateTime().ToString("dd/MMM/yyyy") + "</strong></td></tr>");

        _message.Append("</table><br /></td></tr><tr><td width='360'><br />");

        _message.Append("<table width='100%' border='0' cellpadding='5' cellspacing='0'  class='table_details'>");

        _message.Append("<tr><td width='45%'></td>");
        _message.Append("<td width='55%' align='center' style='background:#e0e0e0; border-bottom:white 1px dashed;'>");
        _message.Append("<img src='" + _insurerimageurl + "' width='120px' /></td></tr>");

        if (_companyName.Trim() != "")
        {
            _message.Append("<tr><td><strong>" + Resources.CarInsuranceResultPage.Insurer + "</strong></td>");
            _message.Append("<td align='center' style='background:#d5d5d5; color:black;' ><strong>" + _companyName + "</strong></td></tr>");
        }

        _message.Append("<tr><td></td>");
        _message.Append("<td align='center' style='background:#d5d5d5;'>" + _package + "</td></tr>");

        _message.Append("<tr><td align='left' style='background:#d5d5d5' ><strong>" + Resources.CarInsuranceResultPage.TotalVMI + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5; color:black; font-size:16px;'><strong>" + _annualprice + "</strong></td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.DEC + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >" + _excess + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.OwnDamage + "</strong></td>");
        _message.Append("<td align='center' style='background:#c5c5c5;'>");

        if (_isDamageShowImage)
            _message.Append("<img src='http://www.comparexpress.com/images/icon/X.png' /></td></tr>");
        else
            _message.Append(_damage + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.Fire + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");

        if (_isFireShowImage)
            _message.Append("<img src='http://www.comparexpress.com/images/icon/X.png' /></td></tr>");
        else
            _message.Append(_fire + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.Theft + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");

        if (_isTheftShowImage)
            _message.Append("<img src='http://www.comparexpress.com/images/icon/X.png' /></td></tr>");
        else
            _message.Append(_theft + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.TPPD + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");
        _message.Append(_tppd + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.TPBIA + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");
        _message.Append(_losspe + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.TPBIP + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");
        _message.Append(_lossuse + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.PADriver + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");
        _message.Append(_padriver + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.MED + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");
        _message.Append(_medicalexp + "</td></tr>");

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.BailBond + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");
        _message.Append(_bailbond + "</td></tr>");

        string imgfloodurl = "http://www.comparexpress.com/images/icon/X.png";

        if (_isFloodCovered)
            imgfloodurl = "http://www.gluaygluay.com/images/icon/flood_car.png";

        _message.Append("<tr><td style='border-bottom:1px solid #ccc;'><strong>" + Resources.CarInsuranceResultPage.FloodCover + "</strong></td>");
        _message.Append("<td align='center' style='background:#d5d5d5' >");
        _message.Append("<img src='" + imgfloodurl + "' /></td></tr>");

        _message.Append("</table><br /><br />");
        _message.Append("<a href='tel:022688222'><img src='http://www.gluaygluay.com/images/banners/hotline_en.png' alt='Call Us at 02 268 8222' width='270' border='0' /></a>");
        _message.Append("<br /><br /><br />");

        _message.Append("<strong>" + Resources.ProposalForm.Remarks + "</strong><br />");
        _message.Append(Resources.ProposalForm.RemarkOne + "<br />");
        _message.Append(Resources.ProposalForm.RemarkTwo + "<br />");
        _message.Append("</td></tr><tr><td id='email_footer'></td>");
        _message.Append("</tr></table><br /><br /><hr />" + Resources.ProposalForm.ThisQuoteis + " <br /><br />");
        _message.Append("<i>" + Resources.ProposalForm.EmailDisclaimer + "</i><hr />");

        if (MyMailManager.SendNotification(_emailList, _title, _message.ToString()))
        {
            Response.Redirect("email_confirm.aspx?type=email&resultid=" + carresultid);
        }
        else
        {
            lblNoResultMessage.Text = "Cannot send mail quote please try again.";
        }
            
    }

    protected void btnApply_Click(object sender, EventArgs e)
    {


    }
    protected void ibtEditQuoteDetail_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect("quotedetails.aspx");
    }

    #region kawna
    private string _url = "http://www.kawna.com/dat/qMotor2.php";
    DataSet dsBrand = new DataSet();
    private bool IsKawnaCar(string makeName)
    {
        MyDatabase _db = new MyDatabase();
        object _result = null;
        Int64 _retValue = 0;

        _result = _db.ExecuteScalarSqlStatement("select COUNT(CarModel)from tblKawnaCar WHERE  CarMake = '" + makeName + "' ");
        if (_result != null)
        {
            _retValue = Convert.ToInt64(_result);
        }
        return _retValue > 0;
    }

    DataSet dsModel = new DataSet();
    private string GetKawnaModelValue(string brandName, string modelName)
    {
        try
        {
            HttpWebRequest request;
            string url = _url + "?t=m&b=" + brandName;
            string responseBody = string.Empty;
            string requestBody = "";
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/xml;charset=utf-8";
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
            request.Accept = "*/*";
            request.Method = "POST";
            request.ContentLength = byteData.Length;
            System.Net.ServicePointManager.Expect100Continue = false;
            request.KeepAlive = false;
            DataSet dsM = new DataSet();
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                dsM.ReadXml(response.GetResponseStream());
            }
            foreach (DataRow dr in dsM.Tables[0].Rows)
            {
                if (dr["M_Text"].ToString().ToLower() == modelName.ToLower())
                    return dr["value"].ToString();
            }
        }
        catch { }

        MyDatabase _db = new MyDatabase();
        DataTable dtKawnaCar = new DataTable();
        dtKawnaCar = _db.GetDataTable("select Distinct CarModelID from tblKawnaCar WHERE CarMake = '" + brandName + "' AND CarModel = '" + modelName + "' ");
        if (dtKawnaCar.Rows.Count > 0)
            return dtKawnaCar.Rows[0]["CarModelID"].ToString();

        return "";
    }
    /// <summary>
    /// Get Minimum Kawna SumInsured
    /// </summary>
    /// <param name="cmake"></param>
    /// <param name="cmodel"></param>
    /// <param name="cyear"></param>
    /// <returns></returns>
    private string GetKawnaSingleSumInsured(string cmake, string cmodel, string cyear)
    {
        if (cmake == "" || cmodel == "" || cyear == "")
            return "";

        try
        {
            HttpWebRequest request;
            string url = _url + "?t=t&b=" + cmake.Trim() + "&m=" + cmodel.Trim() + "&y=" + cyear.Trim();
            string responseBody = string.Empty;
            string requestBody = "";
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/xml;charset=utf-8";
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
            request.Accept = "*/*";
            request.Method = "POST";
            request.ContentLength = byteData.Length;
            System.Net.ServicePointManager.Expect100Continue = false;
            request.KeepAlive = false;

            DataSet dsS = new DataSet();
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                dsS.ReadXml(response.GetResponseStream());
            }

            if (dsS.Tables[0].Rows.Count == 1 && dsS.Tables[0].Rows[0][0].ToString() == "ERR4")
            {
               
            }
            else
            {
                return dsS.Tables[0].Rows[0][0].ToString();
            }
        }
        catch { }

        MyDatabase _db = new MyDatabase();
        DataTable dtKawnaCar = new DataTable();
        dtKawnaCar = _db.GetDataTable("select SumInsured from tblKawnaCar WHERE CarMake = '" + cmake + "' AND CarModelID = " + cmodel + " And Year = " + cyear + " ");
        if (dtKawnaCar.Rows.Count > 0)
            return dtKawnaCar.Rows[0]["SumInsured"].ToString();

        return "";
    }

    private double GetPromotionPrice(double price, int knInsurerId)
    {

        double _ret = 0;
        if (knInsurerId != 61 && knInsurerId != 2 && price >= 5000.00)
        {
            try
            {
                double netPremium = Math.Floor(Math.Round(price / 1.07, 0) / 1.004);
                double discount = netPremium * 5 / 100;
                double duty = Math.Ceiling(netPremium * 0.004);
                double vat = (netPremium + duty) * 0.07;
                _ret = netPremium - discount + duty + vat;
            }
            catch { }
        }
        return _ret;

    }

    #endregion
}
